package com.han.verifycode.utils;

import com.han.verifycode.data.CalcExpression;
import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.JexlExpression;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CalcUtil {
    private static final JexlEngine jexlEngine = new JexlBuilder().create();
    private static final List<String> cs = Stream.of("+,-,*,/".split(",")).collect(Collectors.toList());
    private static final Map<String, String> map = new HashMap<String, String>() {{
        put("+", "+");
        put("-", "-");
        put("*", "x");
        put("/", "÷");
    }};

    /**
     * 计算表达式
     *
     * @param expression
     * @return
     */
    public static Object eval(String expression) {
        JexlExpression jexlExpression = jexlEngine.createExpression(expression);
        Object evaluate = jexlExpression.evaluate(null);
        return evaluate;
    }

    /**
     * 长度表示有几个计算符号
     *
     * @param length
     * @return
     */
    public static CalcExpression randomExpression(int length,int maxNum) {
        Random random = RandomUtil.getRandom();
        CalcExpression ex = new CalcExpression();
        int start = nextInt(maxNum);
        StringBuilder sb = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        sb.append(start + ".0");
        sb2.append(start);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(3);
            String op = cs.get(index);
            String opDesc = map.get(op);
            sb.append(op);
            sb2.append(opDesc);
            int nextNum = nextInt(maxNum);
            sb.append(nextNum);
            sb2.append(nextNum);

        }
        ex.setExpression(sb.toString());
        ex.setDesc(sb2.toString());
        Object result = eval(ex.getExpression());
        Double r = Double.valueOf(result.toString());
        ex.setResult(r.toString().replace(".0", ""));
        return ex;
    }

    /**
     * 得数不能为0
     *
     * @return
     */
    private static Integer nextInt(int maxNum) {
        Random random = RandomUtil.getRandom();
        int num = random.nextInt(maxNum);
        while (num == 0) {
            num = random.nextInt(maxNum);
        }
        return num;
    }

    public static void main(String[] args) {
        int i = 10000;
        while (--i > 1) {
            System.out.println(randomExpression(3,10));

        }
    }


}
